<?php

namespace app\admin\model;

use app\admin\library\Auth;
use fast\Express100;

use think\Db;
use think\Exception;
use think\Model;
use think\Loader;

class PackageExpress extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 表名
    protected $name = 'package_express';

    protected $deleteTime = false;




    /** 获取订单物流信息
     * @param $orderId
     * @param $express_no
     * @return bool|mixed
     */
    public static function getExpressData($orderId,$express_no){
        $data = Db::name('package_express')->where(['orderId'=>$orderId,'express_no'=>$express_no])->find();
        if(empty($data) || empty($data['data'])) return false;

        $nowTime = time();
        $expressData = json_decode($data['data'],true);
        if(empty($expressData) || !is_array($expressData)) return false;
        if(empty($expressData['data'])) return false;
        //如果订单已经签收
        if(isset($data['ischeck']) && $data['ischeck']==1){
            return $expressData;
        }
        //超过2个小时，不再使用数据库数据
        if(($nowTime - $data['updatetime']) > 3600 * 2) return false;
        return $expressData;
    }


    /** 设置，存储物流信息
     * @param $orderId
     * @param $express_no
     * @param $express_name
     * @return bool|mixed
     * @throws \Exception
     */
    public static function setExpressData($orderId,$express_no,$express_name=''){
        if(empty($orderId) || empty($express_no)){
            throw new \Exception('参数有误');
        }

        $data = Express100::getExpressInfo($express_no);
        if(empty($data) || empty($data['data'])){
            throw new Exception('还未有物流信息');
        }
        $nowTime = time();
        $model = PackageExpress::where(['orderId'=>$orderId,'express_no'=>$express_no])->find();
        if($model){
            $model->save(['data'=>json_encode($data),'updatetime'=>$nowTime]);
        }else{
            $model = new PackageExpress();
            $model->save([
                'orderId'=>$orderId,
                'express_no'=>$express_no,
                'express_name'=>$express_name?:"",
                'data'=>json_encode($data),
                'createtime'=>$nowTime,
                'updatetime'=>$nowTime
            ]);
            $model->save();
        }
        return $data;
    }

}
